package prickworlds.gui;

import java.util.ArrayList;

/**
 * base class for a focusable control that can send events
 * 
 * @author Faruk Acibal, Richard Dziambor, Christian Holzreuter, Nicolas Winkler
 * 
 */
public abstract class ActiveControl extends Control {
	/**
	 * list of all {@link ActionListener}s, which receive an event when
	 * {@link performAction} is invoked.
	 */
	protected ArrayList<ActionListener> actionListeners;

	/**
	 * Focusable to handle focus and shit
	 */
	Focusable focus;

	/**
	 * default constructor
	 */
	protected ActiveControl() {
		actionListeners = new ArrayList<ActionListener>();
		focus = new Focusable();
	}

	/**
	 * creates an {@link ActiveControl} from the specified arguments
	 * 
	 * @param x
	 *            the x-coordinate of the upper left corner of the control
	 * @param y
	 *            the y-coordinate of the upper left corner of the control
	 * @param width
	 *            the width of the control
	 * @param height
	 *            the height of the control
	 */
	protected ActiveControl(int x, int y, int width, int height) {
		super(x, y, width, height);
		actionListeners = new ArrayList<ActionListener>();
		focus = new Focusable();
	}

	/**
	 * sends an {@link ActionEvent} to every {@link ActionListener}
	 * 
	 * @param ae
	 *            the {@link ActionEvent} to send
	 */
	protected void performAction(ActionEvent ae) {
		for (int i = 0; i < actionListeners.size(); i++) {
			actionListeners.get(i).actionPerformed(ae);
		}
	}

	/**
	 * creates and sends an {@link ActionEvent} to every {@link ActionListener}
	 */
	protected void performAction() {
		ActionEvent ae = new ActionEvent(this);
		for (int i = 0; i < actionListeners.size(); i++) {
			actionListeners.get(i).actionPerformed(ae);
		}
	}

	/**
	 * adds a new {@link ActionListener} to the control
	 * 
	 * @param al
	 *            the {@link ActionListener} to add
	 */
	public void addActionListener(ActionListener al) {
		actionListeners.add(al);
	}

	/**
	 * removes an {@link ActionListener} from the control
	 * 
	 * @param al
	 *            the {@link ActionListener}
	 * @return {@code true} if the {@link ActionListener} actually existed,
	 *         {@code false} otherwise
	 */
	public boolean removeActionListener(ActionListener al) {
		return actionListeners.remove(al);
	}
}
